// utils/websocket.js
export default class WebSocketService {
  constructor(url, options = {}) {
    this.url = url;
    this.options = options;
    this.socket = null;
    this.isConnected = false;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = options.maxReconnectAttempts || 5;
    this.reconnectInterval = options.reconnectInterval || 3000;

    // 回调函数
    this.onOpenCallback = null;
    this.onMessageCallback = null;
    this.onErrorCallback = null;
    this.onCloseCallback = null;
  }

  connect() {
    if (this.socket && this.isConnected) return;

    this.socket = new WebSocket(this.url);

    this.socket.onopen = (event) => {
      this.isConnected = true;
      this.reconnectAttempts = 0;
      if (this.onOpenCallback) this.onOpenCallback(event);
    };

    this.socket.onmessage = (event) => {
      if (this.onMessageCallback) this.onMessageCallback(event);
    };

    this.socket.onerror = (error) => {
      if (this.onErrorCallback) this.onErrorCallback(error);
    };

    this.socket.onclose = (event) => {
      this.isConnected = false;
      if (this.onCloseCallback) this.onCloseCallback(event);

      // 自动重连逻辑
      if (this.options.autoReconnect && this.reconnectAttempts < this.maxReconnectAttempts) {
        setTimeout(() => {
          this.reconnectAttempts++;
          this.connect();
        }, this.reconnectInterval);
      }
    };
  }

  disconnect() {
    if (this.socket) {
      this.socket.close();
      this.isConnected = false;
    }
  }

  send(data) {
    if (this.socket && this.isConnected) {
      this.socket.send(typeof data === 'object' ? JSON.stringify(data) : data);
    } else {
      console.error('WebSocket is not connected');
    }
  }

  onOpen(callback) {
    this.onOpenCallback = callback;
    return this;
  }

  onMessage(callback) {
    this.onMessageCallback = callback;
    return this;
  }

  onError(callback) {
    this.onErrorCallback = callback;
    return this;
  }

  onClose(callback) {
    this.onCloseCallback = callback;
    return this;
  }
}
